package cn.com.shopec.erp.stock.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.excel.ExcelBaseImport;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.page.PageQuery;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.multiChannel.common.MultiChannelConfig;
import cn.com.shopec.erp.stock.commo.ObjectUtil;
import cn.com.shopec.erp.stock.commo.StockProductException;
import cn.com.shopec.erp.stock.entity.ProductBarCode;
import cn.com.shopec.erp.stock.excel.impl.ProductBarCodeExcelImport;
import cn.com.shopec.erp.stock.service.IProductBarCodeService;
import cn.com.shopec.erp.stock.service.IStockInService;
import cn.com.shopec.erp.stock.service.IStockOutService;
import cn.com.shopec.erp.stock.vo.ProductBarCodeVo;

@Controller
@RequestMapping("stockmanage/productBarCodeContrller")
public class ProductBarCodeContrller {

	/** 日志. */
	private Logger log = Logger.getLogger(ProductBarCodeContrller.class);

	@Resource
	private IStockInService stockInService;

	@Resource
	private IStockOutService stockOutService;

	@Resource
	private IProductBarCodeService productBarCodeService;

	/**
	 * 跳转查询条形码
	 * 
	 * @param productBarCode
	 * @param pageQuery
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("pageFinderProductBarCode")
	public String pageFinderProductBarCode(ProductBarCodeVo productBarCode, PageQuery pageQuery, ModelMap map)
			throws Exception {
		if (!StringUtil.isEmpty(productBarCode.getStockInNo())) {
			map.put("stockIn", stockInService.getStockByNo(productBarCode.getStockInNo()));
			map.put("stockInProductId", productBarCode.getStockInProductId());
			map.put("stockOut", null);
			map.put("stockOutProductId", null);
		} else if (!StringUtil.isEmpty(productBarCode.getStockOutNo())) {
			map.put("stockOut", stockOutService.getStockByNo(productBarCode.getStockOutNo()));
			map.put("stockOutProductId", productBarCode.getStockOutProductId());
			map.put("stockIn", null);
			map.put("stockInProductId", null);
		}
		return "/stock/product_barcode_list";
	}

	/**
	 * ajax查询条形码
	 * 
	 * @param productBarCode
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("ajaxPageFinderProductBarCode")
	@ResponseBody
	public String ajaxPageFinderProductBarCode(ProductBarCodeVo productBarCode, PageQuery pageQuery, ModelMap map) {
		JSONObject jsonObj = new JSONObject();
		PageFinder<ProductBarCodeVo> pageFinder = productBarCodeService.queryProductBarCodeList(productBarCode,
				pageQuery);
		jsonObj.put("Rows", pageFinder.getData());
		jsonObj.put("Total", pageFinder.getRowCount());
		return jsonObj.toJSONString();
	}

	/**
	 * 添加条形码
	 * 
	 * @param productBarCodes
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("addProductBarCode")
	@ResponseBody
	public String addProductBarCode(List<ProductBarCode> productBarCodes, PageQuery pageQuery, ModelMap map) {
		try {
			productBarCodeService.addProductBarCode(productBarCodes);
			return SZSCMConstant.SUCCESS;
		} catch (Exception e) {
			log.error("addProductBarCode" + e.getMessage(), e);
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 删除条形码
	 * 
	 * @param productBarCode
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("deleteProductBarCode")
	@ResponseBody
	public String deleteProductBarCode(ProductBarCodeVo productBarCode, PageQuery pageQuery, ModelMap map) {
		try {
			if (productBarCode.getStockOutProductId() != null) {
				productBarCodeService.cancelBarCodeStateStockOut(productBarCode.getStockOutProductId());
			} else {
				productBarCodeService.deleteProductBarCode(productBarCode.getStockInProductId());
			}
			return SZSCMConstant.SUCCESS;
		} catch (Exception e) {
			log.error("deleteProductBarCode" + e.getMessage(), e);
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 上传条形码
	 * 
	 * @param productBarCode
	 * @param barCodeFile
	 * @return
	 */
	@RequestMapping("importBarCode")
	@ResponseBody
	public String fileUpload(ProductBarCode productBarCode, @RequestParam MultipartFile barCodeFile) {
		if (!barCodeFile.isEmpty()) {
			try {
				ExcelBaseImport loadExcel = new ProductBarCodeExcelImport(barCodeFile.getInputStream(),
						barCodeFile.getOriginalFilename(), 1);
				List<Object> excelData = loadExcel.getList();
				if (!CollectionUtils.isEmpty(excelData) && excelData.size() == productBarCode.getProdQuantity()) {
					Integer stockInType = productBarCode.getStockInType();
					if (ObjectUtil.isNotNull(stockInType)) {
						if (stockInType.equals(SZSCMConstant.STOCKIN_TYPE_1)
								|| stockInType.equals(SZSCMConstant.STOCKIN_TYPE_2)
								|| stockInType.equals(SZSCMConstant.STOCKIN_TYPE_3)) {
							productBarCodeService.importProductBarCodes(productBarCode, excelData);
						} else {
							List<ProductBarCode> data = productBarCodeService.checkBarCodeForPurReturn(productBarCode,
									excelData);
							if (!CollectionUtils.isEmpty(data)) {
								JSONObject jsonObj = new JSONObject();
								jsonObj.put("data", data);
								return jsonObj.toJSONString();
							}
						}
					}
				} else {
					return "prodQuantityFail";
				}
				return SZSCMConstant.SUCCESS;
			} catch (StockProductException stockProductException) {
				return "failMsg:" + stockProductException.getExceptionInfo();
			} catch (Exception e) {
				log.error("fileUpload" + e.getMessage(), e);
			}
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 出库校验条形码
	 * 
	 * @param productBarCode
	 * @param barCodeFile
	 * @return
	 */
	@RequestMapping("checkBarCodeForStockOut")
	@ResponseBody
	public String checkBarCodeForStockOut(ProductBarCode productBarCode, @RequestParam MultipartFile barCodeFile) {
		if (!barCodeFile.isEmpty()) {
			try {
				ExcelBaseImport loadExcel = new ProductBarCodeExcelImport(barCodeFile.getInputStream(),
						barCodeFile.getOriginalFilename(), 1);
				List<Object> excelData = loadExcel.getList();
				if (!CollectionUtils.isEmpty(excelData) && excelData.size() == productBarCode.getProdQuantity()) {
					ProductBarCodeVo data = productBarCodeService.checkBarCodeForStockOut(productBarCode, excelData);
					if (ObjectUtil.isNotNull(data)) {
						JSONObject jsonObj = new JSONObject();
						jsonObj.put("data", data);
						return jsonObj.toJSONString();
					}
					return SZSCMConstant.SUCCESS;
				} else {
					return "prodQuantityFail";
				}
			} catch (Exception e) {
				log.error("checkBarCodeForStockOut" + e.getMessage(), e);
			}
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 下载条形码模板
	 * 
	 * @param response
	 */
	@RequestMapping("dowanloadTemplet")
	public void dowanloadTemplet(HttpServletResponse response) {
		try {
			String configPath = MultiChannelConfig.class.getClassLoader().getResource("/").getPath();
			configPath = java.net.URLDecoder.decode(configPath, "utf-8");
			InputStream inStream = new FileInputStream(configPath + "excelTemplet.xlsx");// 文件的存放路径
			response.reset();
			response.setContentType("bin");
			response.addHeader("Content-Disposition",
					"attachment;filename=" + URLEncoder.encode("条形码模板文件.xlsx", "UTF-8"));
			byte[] b = new byte[100];
			int len;
			while ((len = inStream.read(b)) > 0)
				response.getOutputStream().write(b, 0, len);
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("toProductBarcodeError")
	public String toProductBarcodeError(ModelMap map) {
		return "/stock/product_barcode_error_list";
	}
}
